<?php
/**
 * 导入动作权限
 * User：liujun
 * Date：2022/3/5
 * Time：11:16 AM
 */

namespace Encore\Admin\Actions\Custom;

use Encore\Admin\Actions\Action;
use Encore\Admin\Actions\Response;
use Encore\Admin\Auth\Database\Permission;
use Illuminate\Support\Str;
use Symfony\Component\Finder\Finder;

class ImportActionPermissionAction extends Action
{
    use AutoMatchAdminMenuTrait;

    protected $selector = '.import-action-permission-action';

    public function handle(): Response
    {
        $namespace = app()->getNamespace();
        $actions = [];
        foreach ((new Finder())->in(app_path('Admin/Actions'))
                     ->notName(config('admin.action_permissions.exclude_names'))
                     ->exclude(config('admin.action_permissions.exclude_dirs'))
                     ->files()
                 as $resource
        ) {
            //for permissions slug
            $slug = Str::lower(Str::snake(Str::replace('.php', '', $resource->getBasename()), '.'));
            //get the action classname

            $resource = $namespace
                . Str::of($resource->getPathname())
                    ->after(app_path() . DIRECTORY_SEPARATOR)
                    ->replace('/', '\\')
                    ->replace('.php', '');

            //for permission name
            $name = (new $resource)->name ?? null;

            if ($name && $slug) {
                $actions[] = [
                    'slug'          => $slug,
                    'name'          => $name,
                    'admin_menu_id' => null,
                    'http_method'   => ['POST'],
                ];
            }
        }
        $existSlugs = Permission::query()
            ->where('slug', 'like', '%.action')
            ->orWhere('slug', 'like', '%.export')
            ->pluck('slug')
            ->toArray();

        /**
         * insert data after matched menu id
         */
        $actions = $this->actionsMatch($actions);
        foreach ($actions as $action) {
            if (!in_array($action['slug'], $existSlugs)) {
                Permission::query()->create($action);
            } else {
                if ($action['name']) {
                    //update permission name if action name changed
                    Permission::query()->where('slug', $action['slug'])
                        ->where('name', '!=', $action['name'])
                        ->update(['name' => $action['name']]);
                }
            }
        }
        return $this->response()->success('动作权限批量导入成功')->refresh();
    }

    public function dialog()
    {
        $this->confirm('确认要导入自定义的动作权限吗？');
    }

    public function html(): string
    {
        return '<a href="javascript:;" class="btn btn-sm btn-microsoft import-action-permission-action">导入动作</a>';
    }
}